#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SLInit(SL* ps)
{
	assert(ps);

	SLDataType* p = (SLDataType*)malloc(sizeof(SLDataType) * INIT_CAPACITY);
	if (NULL == p)
	{
		perror("malloc fail");
		exit(1);
	}

	ps->p = p;
	ps->capacity = INIT_CAPACITY;
	ps->size = 0;
}

void SLDestroy(SL* ps)
{
	assert(ps);

	free(ps->p);
	ps->p = NULL;
	ps->capacity = ps->size = 0;
}

void SLPrint(SL* ps)
{
	assert(ps);

	for (int i = 0; i < ps->size; ++i)
	{
		printf("%d ", ps->p[i]);
	}
	printf("\n");
}

static void check_capacity(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		SLDataType* p = (SLDataType*)realloc(ps->p, sizeof(SLDataType) * ps->capacity * 2);
		if (NULL == p)
		{
			perror("relloc fail!");
			exit(1);
		}

		ps->p = p;
		ps->capacity *= 2;
	}
}

void SLPushBack(SL* ps, SLDataType x)
{
	//assert(ps);

	//check_capacity(ps);

	//ps->p[ps->size++] = x;
	SLInsert(ps, ps->size, x);
}

void SLPopBack(SL* ps)
{
	//assert(ps);

	//if (0 != ps->size)
	//{
	//	--ps->size;
	//}

	SLErase(ps, ps->size - 1);
}

static void move_back(SL* ps, int begin, int end)
{
	while (begin < end)
	{
		ps->p[end] = ps->p[end - 1];
		--end;
	}
}

void SLPushFront(SL* ps, SLDataType x)
{
	//assert(ps);
	//check_capacity(ps);

	//move_back(ps, 0, ps->size);

	//ps->p[0] = x;
	//++ps->size;

	SLInsert(ps, 0, x);
}

static void move_front(SL* ps, int begin, int end)
{
	while (begin < end)
	{
		ps->p[begin] = ps->p[begin + 1];
		++begin;
	}
}
void SLPopFront(SL* ps)
{
	//assert(ps);

	//if (0 != ps->size)
	//{
	//	move_front(ps, 0, ps->size);
	//	--ps->size;
	//}
	SLErase(ps, 0);
}
int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; ++i)
	{
		if (ps->p[i] == x)
		{
			return i;
		}
	}

	return -1;
}
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(0 <= pos && pos <= ps->size);

	check_capacity(ps);

	move_back(ps, pos, ps->size);
	ps->p[pos] = x;
	++ps->size;
}
void SLErase(SL* ps, int pos)
{
	assert(ps);

	assert(0 <= pos && pos < ps->size);
	move_front(ps, pos, ps->size);
	--ps->size;
}